import glob
import os.path

from PySide6.QtWidgets import QApplication, QFileDialog, QMainWindow
from pathlib import Path
from ui import Ui_mainwindow
import re

# 在QApplication之前先实例化
# 使用os.path.dirname获取脚本所在的目录
current_working_directory = os.getcwd()


class MainWindow(QMainWindow):
    def __init__(self):
        super().__init__()
        self.ui = Ui_mainwindow()
        self.ui.setupUi(self)

        self.filePath = None

        self.ui.open_dir.clicked.connect(self.opend_dir)
        self.ui.lineEdit_suffixfilter.textChanged.connect(self.show_dir_file)
        self.ui.preview.clicked.connect(self.preview)
        self.ui.exec_rename.clicked.connect(self.exec_rename)
        # self.ui.refresh.clicked.connect(self.refresh)
        self.ui.checkBox.stateChanged.connect(self.show_dir_file)
        self.ui.checkBox_2.stateChanged.connect(self.preview)

    def opend_dir(self):
        if self.filePath == None:
            self.filePath = QFileDialog.getExistingDirectory(self, "选择存储路径",current_working_directory)
        else:
            self.filePath = QFileDialog.getExistingDirectory(self, "选择存储路径", self.filePath)  # 打开上一次路径
        self.show_dir_file()

    def show_dir_file(self):
        if self.filePath == None:
            return

        wildcard_filter_value = [item for item in self.ui.lineEdit_suffixfilter.text().split(",") if item]

        self.file_list = []
        if wildcard_filter_value.__len__() > 0:
            for wildcard in wildcard_filter_value:
                if self.ui.checkBox.isChecked():
                    filelists = [str(path) for path in Path(self.filePath).glob(os.path.join("**", wildcard))]
                else:
                    filelists = [str(path) for path in Path(self.filePath).glob(wildcard)]

                self.file_list.extend(filelists)
        else:
            if self.ui.checkBox.isChecked():
                filelists = [str(path) for path in Path(self.filePath).glob(os.path.join("**", "*"))]
            else:
                filelists = [str(path) for path in Path(self.filePath).glob("*")]
            self.file_list.extend(filelists)
        self.file_list = [path for path in self.file_list if Path(path).is_file()]
        self.file_list.sort()

        # update ui
        self.ui.open_dir.setToolTip(self.filePath)

        self.ui.textBrowser.clear()
        for file_path in self.file_list:
            self.ui.textBrowser.append(str(Path(file_path).name))

        self.ui.statusbar.showMessage(
            f"路径\"{self.filePath}\"下搜索到文件{self.file_list.__len__()}个（通配符条件为：{wildcard_filter_value}）")

    def preview(self):
        self.show_dir_file()
        if self.file_list.__len__() < 1:
            return

        self.name_map = self.eual_exec()

        self.ui.textBrowser_2.clear()
        for key, value in self.name_map.items():
            if self.ui.checkBox_2.isChecked():
                self.ui.textBrowser_2.append(str(Path(value)))
            else:
                self.ui.textBrowser_2.append(str(Path(value).name))

    def eual_exec(self):
        name_map = {}
        eula = self.ui.rename_eula.text()
        for file_path in self.file_list:
            parent_path = str(Path(file_path).parent)
            if "[" in eula and "]" in eula:
                new_filename=str(Path(file_path).name)
                matches = [match  for match in re.findall(r'\[(.*?)\]', eula) if match.__len__() > 0]
                for match in matches:
                    new_filename = new_filename.replace(match, "")
            else:
                new_filename = eula
                if "{filename}" in eula:
                    filename = str(Path(file_path).name)
                    new_filename = new_filename.replace("{filename}", filename)
                if "{parent}" in eula:
                    parent = str(Path(file_path).parent.name)
                    new_filename = new_filename.replace("{parent}", parent)
                if "{stem}" in eula:
                    stem = str(Path(file_path).stem)
                    new_filename = new_filename.replace("{stem}", stem)
                if "{suffix}" in eula:
                    suffix = str(Path(file_path).suffix)[1:]
                    new_filename = new_filename.replace("{suffix}", suffix)

            name_map[file_path] = os.path.join(parent_path, new_filename)

        return name_map

    def exec_rename(self):
        if self.file_list.__len__() < 1:
            return
        success_count = 0
        failed_count = 0
        for key, value in self.name_map.items():
            try:
                Path(key).rename(value)
                success_count += 1
            except:
                failed_count += 1
        if success_count + failed_count > 0:
            self.ui.statusbar.showMessage(f"重命名成功{success_count}个，失败{failed_count}个")
        else:
            self.ui.statusbar.clearMessage()

        self.name_map.clear()
        self.show_dir_file()
        self.ui.textBrowser_2.clear()
    # def refresh(self):
    #     self.show_dir_file()
    #     self.ui.textBrowser_2.clear()


app = QApplication([])
main = MainWindow()
main.show()
app.exec()
